<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="m-b">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/projectManage' }">项目/建筑管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{
                path: '/projectManage/viewProject?projectId=' + projectId,
              }">查看项目</el-breadcrumb-item>
            <el-breadcrumb-item>部署设备</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>
      <el-form :model="formData"
               :rules="rules"
               ref="formRef"
               label-width="120px"
               class="el-form"
               label-position="right">
        <el-form-item label="设备ID"
                      prop="deviceId">
          <el-input v-model="formData.deviceId"
                    maxlength="80"
                    disabled="disabled" />
        </el-form-item>
        <el-form-item label="设备名称"
                      prop="name">
          <el-input v-model="formData.name"
                    maxlength="80" />
        </el-form-item>
        <el-form-item label="所属项目"
                      prop="projectId">
          <el-select filterable
                     v-model="formData.projectId"
                     placeholder="请选择"
                     style="width: 100%"
                     size="medium"
                     disabled="disabled">
            <el-option v-for="item in projectOptions"
                       :key="item.projectId"
                       :label="item.displayName"
                       :value="item.projectId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备地址">
          <el-input v-model="formData.address"
                    maxlength="80" />
        </el-form-item>
        <el-form-item label="设备描述">
          <el-input type="textarea"
                    v-model="formData.description"
                    :rows="2"
                    maxlength="80"
                    placeholder="请输入设备描述"
                    style="width: 100%" />
        </el-form-item>
        <el-form-item label="经纬度">
          <el-input v-model="formData.longitude"
                    maxlength="80"
                    style="width: 30%; margin-right: 20px" />
          <el-input v-model="formData.latitude"
                    maxlength="80"
                    style="width: 30%" />
        </el-form-item>
        <el-form-item label="设备朝向">
          <el-radio-group v-model="formData.direction">
            <el-radio label="EAST">东</el-radio>
            <el-radio label="WEST">西</el-radio>
            <el-radio label="NORTH">北</el-radio>
            <el-radio label="SOUTH">南</el-radio>
            <el-radio label="NORTH_EAST">东北</el-radio>
            <el-radio label="NORTH_WEST">西北</el-radio>
            <el-radio label="SOUTH_WEST">西南</el-radio>
            <el-radio label="SOUTH_EAST">东南</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备图片">
          <div v-for="(item, index) in imgKeys"
               :key="item.imgkey"
               style="float: left; margin-right: 10px"
               class="img-box">
            <div @click="delImg(item, index)"
                 class="close-icon">
              <i class="el-icon-error"></i>
            </div>
            <img :src="item.httpUrl"
                 class="uploadImg"
                 style="border: 1px solid #ccc; width: 300px; height: 220px" />
          </div>
          <el-upload class="upload-demo"
                     drag
                     ref="uploadAdd"
                     action
                     :http-request="uploadImg"
                     :on-success="uploadImgSuccess"
                     :on-remove="handleRemove"
                     multiple
                     show-file-list>
            <!-- <img v-if="imgUrl" :src="imgUrl" class="uploadImg"> -->
            <!-- <div v-else> -->
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <!-- </div> -->

          </el-upload>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button type="primary"
                     :loading="submitLoading"
                     icon="el-icon-check"
                     @click="submit('formRef')">提 交
          </el-button>
          <el-button type="default"
                     icon="el-icon-back"
                     @click="goBack">返 回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { deploy, get } from "@/api/deviceManage";
import { listSimple } from "@/api/projectManage";
import { upload, getImg } from "@/api/common";

export default {
  name: "DeployDevice",
  data() {
    return {
      deviceId: "",
      projectId: "",
      formData: {},
      projectOptions: [],
      submitLoading: false,
      imgKeys: [],
      uploadUrls: [],
      rules: {
        deviceId: [
          { required: true, message: "请输入设备ID", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        projectId: [
          { required: true, message: "请选择所属项目", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.deviceId = this.$route.query.deviceId;
    this.projectId = this.$route.query.projectId;
  },
  mounted() {
    this.getMessage();
    this.getProjectList();
  },
  methods: {
    getImgFun(val) {

      let data = {
        key: val,
      };
      getImg(data).then((res) => {
        for (let i = 0; i < this.imgKeys.length; i++) {
          if (this.imgKeys[i].imgkey == val) {
            this.imgKeys[i].httpUrl = res.value;
          }
        }
      });
    },
    delImg(index) {
      this.imgKeys.splice(index, 1);
    },
    uploadImg(f) {
      let param = new FormData(); //创建form对象
      param.append("file", f.file); //通过append向form对象添加数据
      param.append("type", "DEVICE_PIC"); //添加form表单中其他数据
      upload(param) //上传
        .then((response) => {
          if (response.code == "200") {
            this.imgKeys.push({
              imgkey: response.value.key,
              httpUrl: response.value.url,
            });
            this.$message.success("上传成功!");
            this.close();
          }
        })
        .catch(({ }) => {
          f.onError();
        });
    },
    uploadImgSuccess() {
      this.$message.success("图片上传成功!");
    },
    handleRemove(file, fileList) {
      // 更新缓存文件
      this.$message.success("图片已删除!");
    },
    getMessage() {
      const that = this;
      let data = {
        deviceId: this.deviceId,
      };
      get(data).then((res) => {
        if (res["code"] == 200) {
          that.formData = res.value;
          for (let i = 0; i < this.formData.imageKeys.length; i++) {
            const element = this.formData.imageKeys[i];
            this.imgKeys.push({ imgkey: element, httpUrl: "" });
            this.getImgFun(element);
          }
          if (
            that.formData.project == null ||
            that.formData.project.projectId == null
          ) {
            // that.formData.projectId = "";
          } else {
            that.formData.projectId = that.formData.project.projectId;
          }
        }
      });
    },
    getProjectList() {
      listSimple().then((res) => {
        this.projectOptions = res.value;
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    toProject() {
      this.$router.push(
        "/projectManage/viewProject?projectId=" + this.projectId
      );
    },
    submit(formName) {
      this.submitLoading = true;
      this.$refs[formName].validate((valid) => {
        let imageKeys = this.imgKeys.map((item) => {
          return item.imgkey;
        });
        if (valid) {
          const that = this;
          const data = {
            ...that.formData,
            imageKeys,
          };
          deploy(data).then((res) => {
            if (res["code"] == 200) {
              this.$router.push(
                "/projectManage/viewProject?projectId=" + this.projectId
              );
              that.$message.success("部署成功!");
            } else {
              that.$message(res["msg"]);
            }
          });
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
  },
};
</script>
<style>
.upload-demo .el-upload-dragger {
  border: 1px solid #ccc;
  width: 300px;
  height: 220px;
}
.upload-demo .el-upload-dragger .el-icon-upload {
  line-height: 100px;
}
</style>
<style scoped>
.el-form {
  width: 90%;
  margin: 20px;
}

.uploadImg {
  width: auto;
  height: 100%;
}
.img-box {
  position: relative;
}
.img-box .close-icon {
  background-color: #fff;
  width: 25px;
  height: 25px;
  line-height: initial;
  border-radius: 100%;
  font-size: 25px;
  color: #999;
  position: absolute;
  right: 5px;
  top: 1px;
}
</style>
